R Graph
plot
- Add image to the rmarkdown:
Accumulative Distribution
ggplot(dt, aes(status_day5_num)) + stat_ecdf(geom = "step") +
scale_x_continuous(limits=c(0.8, 8.8)
, breaks=1:8
, labels=levels(dt$status_day5)
, name="Numerical Day 5 Status")Histogram by Group
ggplot(dt, aes(x=avg_daily_prone, fill=treatment)) +
geom_histogram( color="#e9ecef", alpha=0.3, position = 'identity') +
scale_fill_manual(values=c("#69b3a2", "#404080"))Flowchart
library(Wu)
library(tgsify)
readRDS(file="df.RDS") %>%
mutate(consort = case_when(
iculos7d != "ICULOS 7d or more" ~ "2 2 ICU LOS less than 7 days"
, is.na(inptrehabdc) ~ "3 2 Missing Values on Discharge Destination"
, TRUE ~ "4 1 Study population"
)) %>%
le("consort") %>%
two_column_consort("Total Records")ggplot
Pass Column Names to ggplot inside a function
- sym() function turn text into a symbol, like as.name() or as.symbol
- !! function is to unquote
- Use color from a column
library(data.table)
library(ggplot2)
dt <- data.table(A=1:10
, B=1:10
, C=rep(1:5, each=2)
, sex=factor(rep(c("M", "F"), each=5))
)
clrs <- c("#FF0000", "#00FF00")
dt[["varcolor"]] <- clrs[as.numeric(dt$sex)]
plt <- function(x, y, group){
x <- sym(x)
y <- sym(y)
ggplot(dt, aes(x=!!x, y=!!y)) +
geom_point() +
facet_wrap( as.formula(paste0("~", group)), nrow = 1)
}
plt("A", "B", "sex")ggplot(dt, aes(A, B, colour=varcolor)) + geom_point() +
scale_colour_identity()ggplot(dt, aes(x=C, group=sex, colour=varcolor, fill=varcolor)) +
geom_bar() + scale_colour_identity() + scale_fill_identity()Stacked Bar Charts
p <- ggplot(fdt2, aes(day_assessment_icu)) +
geom_bar() +
geom_bar(aes(fill = state_daily4_locf))
pStacked Bar Charts by Percentage
ggplot(fdt3, aes(x = factor(day_assessment_icu)
, fill = state_daily4_locf)) +
geom_bar(position="fill") +
facet_wrap( ~ race_ethnicity, ncol=2)Forest Plot
dt <- data.table(
name=factor(LETTERS[1:8], levels=LETTERS[1:8], ordered=TRUE)
, coef_value=1:8
, coef_value_lower=(1:8) - 0.5
, coef_value_upper=(1:8) + 0.5
)
dt <- dt[, name_label := factor(paste0(name, " ", "CI"))]
dt <- dt[, num_rep := 22 - nchar(round(coef_value, 4)) ]
## png(file="forestplot.png", width = 2400, height = 1200, res = 300)
p <- ggplot(dt
, aes(y = name_label
, x = coef_value
, xmin = coef_value_lower
, xmax = coef_value_upper
)) +
geom_vline(xintercept=1, color='grey', linetype='dashed',size=0.7) +
geom_errorbarh(height=0.2,color="#333333",size=0.8) +
geom_point(color = "#666666", size=2, shape=15) +
scale_x_continuous(limits=c(0,9)
, breaks=c(0,1,2,5, 9)
, name='Odds Ratio') +
## p <- p + scale_y_discrete(labels = "Y AXIS", sec.axis = dup.axis())
ylab("") +
theme_bw() +
theme(axis.ticks = element_blank()
, panel.grid.major = element_blank()
, panel.grid.minor = element_blank()
) +
coord_cartesian(xlim=c(0, 9))
p## dev.off()Export Plot
png(file = "filname.png", width = 2400, height = 1200, res = 300)
p
dev.off()Forest Plot Log Scale
png(file="forestplot_irf.png", width = 2400, height = 1200, res = 300)
p <- ggplot(dt
, aes(y = name_label
, x = coef_value
, xmin = coef_value_lower
, xmax = coef_value_upper
))
p <- p + geom_vline(xintercept=1, color='grey', linetype='dashed',size=0.7)
p <- p + geom_errorbarh(height=0.2,color="#333333",size=0.8)
p <- p + geom_point(color = "#666666",size=1,shape=15)
p <- p + scale_x_continuous(limits=c(0.1,4), breaks=c(0.1, 0.2, 0.5,1,2,3, 4), name='Adjusted Odds Ratio (IPR)')
## p <- p + scale_y_discrete(labels = "Y AXIS", sec.axis = dup.axis())
p <- p + ylab("")
p <- p + theme_bw()
p <- p + theme(axis.ticks = element_blank()
, panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)
p <- p + coord_cartesian(xlim=c(0, 4)) + coord_trans(x="log")
p
dev.off()
include_graphics("forestplot_irf.png")Cell Plot
- Plot discrete daily progression states
library(ggplot2)
dt <- data.table(
id=1:10
, day=rep(1:28, each=10)
, state=sample(c("A", "B", "C", "D", "E", NA), 28 * 10, replace = TRUE)
)
dt <- dt[, state := factor(state, levels=c("A", "B", "C", "D", "E"), ordered = TRUE)]
clrs <- c("#2EAEE6"
## , "#2EE6CA"
## , "#2EE677"
, "#37E62E"
## , "#8AE62E"
, "#DCE62E"
, "#E69C2E"
, "#E6492E"
## , "#aaaaaa"
)
ggplot(dt, aes(x=day, y=id)) +
geom_tile(aes(fill=state, height=(1)), size=1) +
scale_y_discrete() +
scale_fill_manual(values = clrs)linecolor <- "#999999"
ggplot(dt, aes(y=id,x=day)) +
geom_point(aes(fill=state), colour="transparent", shape=22, size=4) +
scale_fill_manual(values = clrs)+
geom_line(aes(group = id), colour=linecolor, alpha=0.5) +
scale_x_continuous(breaks=c(7, 14, 21, 28)) +
scale_y_continuous(breaks=c(1, 3, 5, 7, 9)) +
labs(title = "Title. \n Discrete Time Plot", x="Day", y="ID") +
geom_vline(xintercept=c(7, 14), colour=linecolor,linetype="dashed") +
geom_vline(xintercept=21,colour=linecolor,linetype="dashed") +
theme(panel.background = element_rect(fill = "transparent")
, plot.background = element_rect(fill = "transparent", color = NA)
, panel.grid.major = element_blank()
, panel.grid.minor = element_blank()
, legend.background = element_rect(fill = "transparent")
, legend.box.background = element_rect(fill = "transparent")
, legend.position = 'top'
, plot.margin=unit(c(1,2,1,2),"cm")
) +
coord_fixed(ratio = 3 / 2
, xlim = c(0.5, 28.5)
, ylim = c(0.5, 10.5)
, expand = FALSE) +
guides(fill = guide_legend(nrow = 1))Progression Bar Plot
rm(list=ls())
library(ggplot2)
library(data.table)
dt <- data.table(
id=rep(1:100, each=28)
, day=rep(1:28, 100)
, state=sample(c("A", "B", "C", "D", "E"), 28 * 100, replace = TRUE)
, treatment=rep(c("Case", "Control"), each=28 * 100 / 2)
)
dt <- dt[, state := factor(state, levels=c("A", "B", "C", "D", "E"), ordered = TRUE)]
clrs <- c("#2EAEE6"
## , "#2EE6CA"
## , "#2EE677"
, "#37E62E"
## , "#8AE62E"
, "#DCE62E"
, "#E69C2E"
, "#E6492E"
## , "#aaaaaa"
)
ggplot(dt, aes(x = factor(day), fill = state)) + geom_bar(position = "fill") +
facet_wrap(~treatment) + scale_fill_manual(values = clrs) +
xlab("Day State by Treatment") +
ylab("Proportions")ggplot(dt, aes(x=day, fill = state)) + geom_bar() +
facet_wrap(~treatment) + scale_fill_manual(values = clrs) +
labs(x="Day State by Treatment"
, y="Count"
, title="Progression by Treatment"
) +
scale_x_continuous(breaks=c(7, 14, 21, 28)) +
scale_y_continuous(breaks=c(10, 20, 30, 40, 50)) +
theme(panel.background = element_rect(fill = "transparent")
, plot.background = element_rect(fill = "transparent", color = NA)
, panel.grid.major = element_blank()
, panel.grid.minor = element_blank()
, legend.background = element_rect(fill = "transparent")
, legend.box.background = element_rect(fill = "transparent")
, legend.position = 'top'
, plot.margin=unit(c(1,2,1,2),"cm")
) +
coord_fixed(ratio = 3 / 2
## , xlim = c(0.5, 28.5)
## , ylim = c(0.5, 10.5)
, expand = FALSE) +
guides(fill = guide_legend(nrow = 1))ggplot(dt, aes(x = factor(treatment), fill = state)) + geom_bar() +
facet_wrap(~factor(day), nrow=1) + scale_fill_manual(values = clrs) +
labs(x="Day State by Treatment"
, y="Count"
, title="Progression by Day"
) +
## scale_x_continuous(breaks=c(7, 14, 21, 28)) +
## scale_y_continuous(breaks=c(10, 20, 30, 40, 50)) +
theme(panel.background = element_rect(fill = "transparent")
, plot.background = element_rect(fill = "transparent", color = NA)
, panel.grid.major = element_blank()
, panel.grid.minor = element_blank()
, legend.background = element_rect(fill = "transparent")
, legend.box.background = element_rect(fill = "transparent")
, legend.position = 'top'
, plot.margin=unit(c(1,2,1,2),"cm")
) +
## coord_fixed(ratio = 3 / 2
## , xlim = c(0.5, 28.5)
## , ylim = c(0.5, 10.5)
## , expand = FALSE) +
guides(fill = guide_legend(nrow = 1))Animation
gganimate
library(ggplot2)
library(gganimate)
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
# Here comes the gganimate code
transition_states(
gear,
transition_length = 2,
state_length = 1
) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out')library(gapminder)
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
facet_wrap(~continent) +
# Here comes the gganimate specific bits
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
transition_time(year) +
ease_aes('linear')Color
Hue Saturation Luminance (HSL)
- fig.width=7 inch
- fig.height=14 inch
- dpi=300
library(ggplot2)
dt <- expand.grid(seq(0, 340, 20), seq(0, 100, 10), seq(0, 100, 10))
dt <- as.data.table(dt)
colnames(dt) <- c("Hue", "Saturation", "Luminance")
## dt <- dt[, clr := hcl(Hue, Chroma, Luminance)]
dt <- dt[, clr := hsv(Hue / 360, Saturation / 100, Luminance / 100)]
ggplot(dt, aes(x=Saturation, y=Luminance, colour=clr)) +
geom_point(size=3) +
scale_color_identity() +
scale_x_continuous(breaks=seq(0, 100, 10)) +
scale_y_continuous(breaks=seq(0, 100, 10)) +
facet_wrap( ~ Hue, nrow=6)plotly
Radar Chart
dt <- readRDS(file="df.RDS")
rl <- dt[, .(m_mmdhp=median(sqrt(mmdhp_score_imp), na.rm = TRUE)
, m_js=median(edmcq_js_score_imp, na.rm = TRUE)
, ms_clt=median(edmcq_js_score_imp, na.rm = TRUE)
, ms_ldr=median(edmcq_ldr_score_imp, na.rm = TRUE)
, m_eol=median(edmcq_eol_score_imp, na.rm = TRUE)
)
, by = list(gender_q3.factor)
][order(gender_q3.factor)]
rl$m_mmdhp2 <- rl$m_mmdhp
dms <- c("MMD-HP", "Job Strain"
, "Safety Culture"
, "Leadership Culture"
, "End of Life"
, "MMD-HP"
)
opc <- 0.5
fig <- plot_ly(
type = 'scatterpolar',
fill = 'toself'
)
fig <- fig %>%
add_trace(
r = t(rl[1, 2:7, drop = TRUE])
, theta = dms
, name = rl$gender_q3.factor[1]
, opacity = opc
)
fig <- fig %>%
add_trace(
r = t(rl[2, 2:7, drop = TRUE])
, theta = dms
, name = rl$gender_q3.factor[2]
, opacity = opc
)
fig <- fig %>%
layout(
polar = list(
radialaxis = list(
visible = T,
range = c(0, 4)
)
)
)
figOverlay Histogram
library(plotly)
p1 <- dt[mg_tp0.factor == "Yes"]$pred
p0 <- dt[mg_tp0.factor == "No"]$pred
plot_ly(alpha = 0.5, xbins = list(start = 0, end = 1, size = 0.02)) %>%
add_histogram(x = ~ p1
, name = "Magnesium"
, inherit = TRUE
## , xbins = seq(0, 1, 0.05)
) %>%
add_histogram(x = ~ p0
, name = "No"
, inherit = TRUE
## , xbins = seq(0, 1, 0.05)
) %>%
layout(barmode = "overlay"
, xaxis = list(title = paste0("Predicted Probabilities of Being Treated with Magnesium (AUC = ",format(r$auc,digits = 3), ")"),
zeroline = FALSE),
yaxis = list(title = "Count",
zeroline = FALSE))Computing Environment
sessionInfo()R version 4.0.3 (2020-10-10) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.5 LTS
Matrix products: default BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
locale: [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages: [1] stats graphics grDevices utils datasets methods base
other attached packages: [1] gapminder_0.3.0 gganimate_1.0.7 Wu_0.0.0.9000
[4] flexdashboard_0.5.2 lme4_1.1-26 Matrix_1.2-18
[7] mgcv_1.8-33 nlme_3.1-149 png_0.1-7
[10] scales_1.1.1 nnet_7.3-14 labelled_2.8.0
[13] kableExtra_1.3.4 plotly_4.9.3 gridExtra_2.3
[16] ggplot2_3.3.3 DT_0.18 tableone_0.12.0
[19] magrittr_2.0.1 lubridate_1.7.10 dplyr_1.0.5
[22] plyr_1.8.6 data.table_1.14.0 rmdformats_1.0.3
[25] knitr_1.33
loaded via a namespace (and not attached): [1] httr_1.4.2 sass_0.3.1 tidyr_1.1.3 jsonlite_1.7.2
[5] viridisLite_0.4.0 splines_4.0.3 bslib_0.2.4 assertthat_0.2.1 [9] statmod_1.4.35 highr_0.9 progress_1.2.2 yaml_2.2.1
[13] pillar_1.6.0 lattice_0.20-41 glue_1.4.2 digest_0.6.27
[17] rvest_1.0.0 minqa_1.2.4 colorspace_2.0-0 htmltools_0.5.1.1 [21] survey_4.0 pkgconfig_2.0.3 gifski_0.8.6 haven_2.4.1
[25] bookdown_0.22 purrr_0.3.4 webshot_0.5.2 svglite_2.0.0
[29] tweenr_1.0.2 tibble_3.1.1 farver_2.1.0 generics_0.1.0
[33] ellipsis_0.3.2 withr_2.4.2 lazyeval_0.2.2 survival_3.2-7
[37] crayon_1.4.1 evaluate_0.14 fansi_0.4.2 MASS_7.3-53
[41] forcats_0.5.1 xml2_1.3.2 prettyunits_1.1.1 tools_4.0.3
[45] hms_1.0.0 mitools_2.4 lifecycle_1.0.0 stringr_1.4.0
[49] munsell_0.5.0 compiler_4.0.3 jquerylib_0.1.4 systemfonts_1.0.1 [53] rlang_0.4.11 grid_4.0.3 nloptr_1.2.2.2 rstudioapi_0.13
[57] htmlwidgets_1.5.3 labeling_0.4.2 rmarkdown_2.7 boot_1.3-25
[61] gtable_0.3.0 DBI_1.1.1 R6_2.5.0 utf8_1.2.1
[65] stringi_1.5.3 Rcpp_1.0.6 vctrs_0.3.8 tidyselect_1.1.0 [69] xfun_0.22